package com.Spring.SpringSpms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.Spring.SpringSpms.model.Client;

public class ClientDAOImpl implements ClientDAO{

	private JdbcTemplate jdbcTemplate;
	
	public ClientDAOImpl(DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public void saveOrUpdate(Client client) {
		if (client.getClient_id() > 0) {
			// update
			String sql = "UPDATE client set client_name=?, company_name=? where client_id=?";
			jdbcTemplate.update(sql, client.getClient_name(),client.getCompany_name(), client.getClient_id());
		}
		else
		{
			//insert
			String sql="insert into Client(client_name,company_name) values(?,?)";
			jdbcTemplate.update(sql, client.getClient_name(),client.getCompany_name());
		}
	}

	@Override
	public void delete(int clientId) {
		String sql = "DELETE FROM client WHERE client_id=?";
		jdbcTemplate.update(sql, clientId);
	}

	@Override
	public Client get(int clientId) {
		String sql = "SELECT * FROM client WHERE client_id=" + clientId;
		return jdbcTemplate.query(sql, new ResultSetExtractor<Client>() {

			@Override
			public Client extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				if (rs.next()) {
					Client client = new Client();
					
					client.setClient_id(rs.getInt("client_id"));
					client.setClient_name(rs.getString("client_name"));
					client.setCompany_name(rs.getString("company_name"));
					
					return client;

				}
				return null;
			}
		});
	}

	@Override
	public List<Client> list() {
		String sql = "select * from Client";
		List<Client> listClient = jdbcTemplate.query(sql, new RowMapper<Client>() {

			@Override
			public Client mapRow(ResultSet rs, int rowNum) throws SQLException {
				//Employee aEmployee= new Employee();
				Client client = new Client();
				
				client.setClient_id(rs.getInt("client_id"));
				client.setClient_name(rs.getString("client_name"));
				client.setCompany_name(rs.getString("company_name"));
				
				return client;
			}		
		});
		return listClient;
	}

}
